package com.yht.weblog.admin.config;

import com.yht.weblog.jwt.config.JwtAuthenticationSecurityConfig;
import com.yht.weblog.jwt.filter.TokenAuthenticationFilter;
import com.yht.weblog.jwt.handler.RestAccessDeniedHandler;
import com.yht.weblog.jwt.handler.RestAuthenticationEntryPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author: yht
 * @date: 2023/12/7 14:53
 * @description: Spring Security 配置类
 **/
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationSecurityConfig jwtAuthenticationSecurityConfig;

    @Autowired
    private RestAuthenticationEntryPoint authEntryPoint;

    @Autowired
    private RestAccessDeniedHandler deniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 禁用CSRF保护
        http.csrf().disable()
                // 禁用表单登录
                .formLogin().disable()
                // 应用自定义的JWT认证配置
                .apply(jwtAuthenticationSecurityConfig)
                // 限制/admin/**路径需要认证
                .and().authorizeHttpRequests()
                .mvcMatchers("/admin/**").authenticated()
                // 其他请求允许所有人访问
                .anyRequest().permitAll()
                .and()
                .httpBasic().authenticationEntryPoint(authEntryPoint) // HTTP基本认证的入口点
                .and()
                .exceptionHandling().accessDeniedHandler(deniedHandler) // 权限拒绝处理程序
                .and()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 禁止创建会话
                .and()
                .addFilterBefore(tokenAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    }


    /**
     * 创建Token身份验证过滤器
     *
     * @return Token身份验证过滤器实例
     */
    @Bean
    public TokenAuthenticationFilter tokenAuthenticationFilter() {
        return new TokenAuthenticationFilter();
    }

}
